#include <iostream>
#include <fstream>

extern "C" {
#include <time.h>
#include <stdlib.h>
}

using namespace std;

int index(int n, double *arrin, int *indx) {
  
  int l,j,ir,indxt,i;
  double q;
  
  for (j=1;j<=n;j++) 
    {
      indx[j]=j;
    }
  
  l=(n >> 1) + 1;
  ir=n;
  for (;;) {
    if (l > 1)
      q=arrin[(indxt=indx[--l])];
    else {
      q=arrin[(indxt=indx[ir])];
      indx[ir]=indx[1];
      if (--ir == 1) {
	indx[1]=indxt;
	return(0);
      }
    }
    i=l;
    j=l << 1;
    while (j <= ir) {
      if (j < ir && arrin[indx[j]] < arrin[indx[j+1]]) j++;
      if (q < arrin[indx[j]]) {
	indx[i]=indx[j];
	j += (i=j);
      }
      else j=ir+1;
    }
    indx[i]=indxt;
  }
}

int main(int argc, char **argv) {

  if (argc < 2) {
    cout << "usage: ./index n" << endl;
    return 1;
  }

  int peaks = atoi(argv[1]);

  double *m = new double[peaks];
  int *n = new int[peaks];

  ifstream ifs;
  ifs.open("lista");

  for (int i = 0; i < peaks; i++) {
    ifs >> m[i];
    printf("%f\n", m[i]);
  }

  ifs.close();

  index(peaks, m-1, n-1);

  cout << "---" << endl;

  for (int i = 0; i < peaks; i++)
    printf("%f\n", m[n[i]-1]);

  delete []m;
  delete []n;

  return 0;

}
